﻿using System.Collections.Generic;
using System.Linq;
using NLog;

namespace ComHlp.PerformanceToolz
{
    public static class PerformanceTracker
    {
        /// <summary> Logger </summary>
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();

        /// <summary> stopwatches currently running </summary>
        private static readonly List<ItxStopwatch> StopWatches = new List<ItxStopwatch>();


        /// <summary> start performance trace </summary>
        /// <param name="traceType"></param>
        public static void Start(ItxTraceType traceType)
        {
            if (traceType == ItxTraceType.Unknown)
            {
                Log.Error("Trace type is not set!");
                return;
            }

            if (StopWatches.Any(x => x.TraceType == traceType))
            {
                Log.Error($"Trace already running for {traceType}");
                return;
            }

            // start watch and add to list
            ItxStopwatch stopWatch = new ItxStopwatch(traceType);
            StopWatches.Add(stopWatch);
            stopWatch.Start();
        }


        /// <summary> stop performance trace for passed tracetype </summary>
        /// <param name="traceType"></param>
        public static void Stop(ItxTraceType traceType)
        {
            // check if we can find a stopwatch for passed tracetype
            var stopWatch = StopWatches.FirstOrDefault(x => x.TraceType == traceType);
            if (stopWatch == null)
            {
                Log.Trace($"{traceType} not running!");
                return;
            }

            // found one - stop and remove from list
            stopWatch.Stop();

            // output measured time
            Log.Trace($"{traceType}: {stopWatch.ElapsedMilliseconds}ms");

            // remove from list
            StopWatches.Remove(stopWatch);
        }
    }
}